package com.hup.utils.commons.thread;

import lombok.extern.log4j.Log4j2;

/**
 * 自带任务线程的,代理PausableTask全生命周期的TimeCat
 * @author hugan
 * @date 2020/4/6
 */
@Log4j2
public class TimeCatStarter extends TimeCat {

    private PausableTask pausableTask;

    /**
     * @param threadSafeStrict {@link PausableTask#threadSafeStrict}
     */
    public TimeCatStarter(boolean threadSafeStrict) {
        super(new PausableTask(threadSafeStrict));
        pausableTask = getPausableTask();
    }

    public void doPause() {
        pausableTask.doPause();
    }

    public void doResume() {
        pausableTask.doResume();
    }

    public void doCancel() {
        pausableTask.doCancel();
    }

    public boolean isRunning() {
        return pausableTask.isRunning();
    }

    public void start(Object caller, StarterHandler handler) {
        start(caller.getClass().getSimpleName() + "-" + Integer.toHexString(caller.hashCode()), handler);
    }

    public void start(String threadName, StarterHandler handler) {
        if (isRunning()) {
            throw new IllegalArgumentException("已启动的任务未结束");
        }
        new Thread(threadName) {
            @Override
            public void run() {
                try {
                    pausableTask.doStart();
                    handler.run(TimeCatStarter.this);
                } catch (Exception e) {
                    handler.onException(e);
                } finally {
                    pausableTask.taskFinished();
                }
            }
        }.start();
    }

    /**
     * 取消已有任务(若存在),且等待任务结束,然后重新启动新任务
     */
    public void restart(Object caller, StarterHandler handler) {
        doCancel();
        pausableTask.waitUntilFinish();
        log.debug("restart");
        if (caller instanceof String) {
            start((String) caller, handler);
        } else {
            start(caller, handler);
        }
    }

    public interface StarterHandler {
        void run(TimeCatStarter starter);

        void onException(Exception e);
    }

}
